package com.zoffy.ybuhelper.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zoffy.ybuhelper.R;
import com.zoffy.ybuhelper.fragment.AddItemFragment;
import com.zoffy.ybuhelper.fragment.UpdateFragment;
import org.jetbrains.annotations.NotNull;

public abstract class ItemControlFragment extends UpdateFragment {
    protected RecyclerView recyclerView;
    protected FragmentManager fragmentManager;
    private String type;
    private String topBarText;
    @SuppressLint("InflateParams")
    private View view;

    public ItemControlFragment(String type,String topBarText){
        this.type=type;
        this.topBarText=topBarText;
    }
    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_menu_control,null,false);
        init();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        update();
    }

    /**
     * 该抽象方法用于为dataList赋值
     */
    protected abstract void dataInit();
    /**
     * 该方法用于显示删除按钮
     */
    protected abstract void showDelete();

    /**
     * 该方法需要为一个名为 recyclerView 的对象添加Adapter和LayoutManager
     */
    protected abstract void adapterInit();

    private void init() {
        fragmentManager=this.getChildFragmentManager();
        recyclerView = view.findViewById(R.id.recyclerview);
        TextView topBar =view.findViewById(R.id.top_bar);
        topBar.setText(topBarText);
        dataInit();
        adapterInit();
        buttonInit();

    }
    protected class addItemListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            AddItemFragment childFragment=new AddItemFragment();
            Bundle bundle=new Bundle();
            bundle.putString("type",type);
            childFragment.setArguments(bundle);
            childFragment.show(fragmentManager,"add_item_dialog");
        }
    }


    private void buttonInit(){
        Button deleteButton=view.findViewById(R.id.show_delete);
        Button addButton=view.findViewById(R.id.add_item);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDelete();
            }
        });
        addButton.setOnClickListener(new addItemListener());
    }

}